#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>

int tickes = 1000;

//静态/全局实现的锁是不需要销毁的
// pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;//互斥锁是具有原子性的

struct data
{
    std::string _name;
    pthread_mutex_t* _lock;
};

void* routine(void* args)
{
    // std::string name = static_cast<const char*>(args);
    data *d = static_cast<data*>(args);
    while(true)
    {
        //所有的线程都需要申请锁
        // pthread_mutex_lock(&glock);//上锁
        pthread_mutex_lock(d->_lock);//上锁
        if(tickes > 0)
        {
            usleep(1000);
            printf("%s : %d\n", d->_name.c_str(), tickes--);
            pthread_mutex_unlock(d->_lock);//解锁

            // printf("%s : %d\n", name.c_str(), tickes--);
            // pthread_mutex_unlock(&glock);//解锁
        }
        else
        {
            pthread_mutex_unlock(d->_lock);//解锁
            // pthread_mutex_unlock(&glock);//解锁
            break;
        }
    }

    return (void*)0;
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);

    pthread_t t1, t2, t3, t4;

    data d1 = {"thread-1", &lock};
    pthread_create(&t1, nullptr, routine, (void*)&d1);

    data d2 = {"thread-2", &lock};
    pthread_create(&t2, nullptr, routine, (void*)&d2);

    data d3 = {"thread-3", &lock};
    pthread_create(&t3, nullptr, routine, (void*)&d3);

    data d4 = {"thread-4", &lock};
    pthread_create(&t4, nullptr, routine, (void*)&d4);


    // pthread_create(&t1, nullptr, routine, (void*)"thread-1");
    // pthread_create(&t2, nullptr, routine, (void*)"thread-2");
    // pthread_create(&t3, nullptr, routine, (void*)"thread-3");
    // pthread_create(&t4, nullptr, routine, (void*)"thread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    pthread_mutex_destroy(&lock);


    return 0;
}